package com.lch.base.net.converter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * explain
 *
 * @author lee(29487113@qq.com) on 17/10/28
 */
public class CustomResponseConverterFactory extends Converter.Factory {

    public static CustomResponseConverterFactory create() {
        return create(new Gson());
    }


    public static CustomResponseConverterFactory create(Gson gson) {
        if (gson == null) throw new NullPointerException("sGson == null");
        return new CustomResponseConverterFactory(gson);
    }

    private final Gson gson;

    private CustomResponseConverterFactory(Gson gson) {
        this.gson = gson;
    }



    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        //返回我们自定义的Gson响应体变换器
        return new CustomResponseBodyConverter<>(gson, type);


        //系统方法。。为什么
//         TypeAdapter<?> adapter = sGson.getAdapter(TypeToken.get(type));
//        return new GsonResponseBodyConverter<>(sGson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomGsonRequestBodyConverter<>(gson, adapter);
    }
}
